#!/bin/bash
# Flask JWT SECRET_KEY 增强修复脚本
# 支持多种部署环境的Flask应用重启

echo "🔧 开始修复Flask JWT配置..."

# 检查Flask应用目录是否存在
if [ ! -d "/www/wwwroot/flask-auth" ]; then
    echo "❌ Flask应用目录不存在: /www/wwwroot/flask-auth"
    echo "请检查应用路径是否正确"
    exit 1
fi

cd /www/wwwroot/flask-auth

# 备份原始配置
echo "📋 备份原始配置文件..."
cp app/config.py app/config.py.backup.$(date +%Y%m%d_%H%M%S)
echo "✅ 配置文件已备份"

# 更新SECRET_KEY
echo "🔑 更新SECRET_KEY配置..."
NEW_SECRET_KEY="aqm-jwt-secret-1749456354171-rLD9xAdYFvBlNXa8vop3Um9zJ6l9V8qDSkhBbzVwVbCsHKvOaNsWiFmi34VpNlDD"

# 使用更精确的sed命令
sed -i "s/SECRET_KEY = os.getenv('SECRET_KEY', '[^']*')/SECRET_KEY = os.getenv('SECRET_KEY', '$NEW_SECRET_KEY')/g" app/config.py

# 验证配置是否更新成功
if grep -q "$NEW_SECRET_KEY" app/config.py; then
    echo "✅ SECRET_KEY配置更新成功"
else
    echo "⚠️ 自动更新失败，尝试手动替换..."
    # 备选方案：直接替换整行
    sed -i "/SECRET_KEY = os.getenv('SECRET_KEY'/c\    SECRET_KEY = os.getenv('SECRET_KEY', '$NEW_SECRET_KEY')" app/config.py
fi

# 创建或更新环境变量文件
echo "📄 设置环境变量..."
cat > .env << EOF
# Flask应用环境变量配置
SECRET_KEY=$NEW_SECRET_KEY
MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_USER=test2
MYSQL_PASSWORD=123456
MYSQL_DB=test2
LOG_LEVEL=INFO
EOF
echo "✅ 环境变量文件已创建"

# 尝试多种方式重启Flask应用
echo "🔄 尝试重启Flask应用..."

restart_success=false

# 方式1: supervisorctl
if command -v supervisorctl > /dev/null 2>&1; then
    echo "尝试使用supervisorctl重启..."
    if supervisorctl restart flask_auth 2>/dev/null; then
        echo "✅ supervisorctl重启成功"
        restart_success=true
    else
        echo "⚠️ supervisorctl重启失败，尝试其他方式"
    fi
fi

# 方式2: systemctl
if [ "$restart_success" = false ] && command -v systemctl > /dev/null 2>&1; then
    echo "尝试使用systemctl重启..."
    for service_name in flask-auth flask_auth flask-app; do
        if systemctl restart $service_name 2>/dev/null; then
            echo "✅ systemctl重启成功: $service_name"
            restart_success=true
            break
        fi
    done
fi

# 方式3: pkill + 重新启动
if [ "$restart_success" = false ]; then
    echo "尝试使用pkill重启Flask进程..."
    pkill -f "python.*app.py\|python.*run.py\|flask\|gunicorn.*flask" 2>/dev/null
    sleep 2
    
    # 尝试重新启动
    if [ -f "run.py" ]; then
        echo "找到run.py，启动Flask应用..."
        nohup python3 run.py > flask.log 2>&1 &
        restart_success=true
    elif [ -f "app.py" ]; then
        echo "找到app.py，启动Flask应用..."
        nohup python3 app.py > flask.log 2>&1 &
        restart_success=true
    fi
fi

# 方式4: 宝塔面板重启提示
if [ "$restart_success" = false ]; then
    echo "⚠️ 自动重启失败，请手动重启Flask应用："
    echo "1. 如果使用宝塔面板: 网站 → 找到flask-auth站点 → 重启"
    echo "2. 如果使用PM2: pm2 restart flask-auth"
    echo "3. 如果使用Docker: docker restart <container_name>"
    echo "4. 手动重启: cd /www/wwwroot/flask-auth && python3 run.py"
fi

# 等待应用启动
echo "⏳ 等待Flask应用启动..."
sleep 5

# 测试API连通性
echo "🧪 测试API连通性..."
if curl -s -o /dev/null -w "%{http_code}" "http://localhost:5000/api/auth/test" | grep -q "200"; then
    echo "✅ Flask应用运行正常"
elif curl -s -o /dev/null -w "%{http_code}" "https://zmyzmy.xin/api/auth/test" | grep -q "200"; then
    echo "✅ Flask应用运行正常 (通过域名访问)"
else
    echo "⚠️ API测试失败，可能需要手动检查应用状态"
fi

echo ""
echo "🎉 JWT配置修复完成！"
echo "新的SECRET_KEY: $NEW_SECRET_KEY"
echo ""
echo "📝 接下来请："
echo "1. 确认Flask应用已重启"
echo "2. 使用前端修复工具测试API访问"
echo "3. 如果仍有问题，检查应用日志: tail -f logs/app.log"
